package cn.nawang.ebeim.client;


import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.esotericsoftware.minlog.Log;

import cn.nawang.ebeim.client.bean.BreakPointQueue;
import cn.nawang.ebeim.client.bean.ClientConfiguration;
import cn.nawang.ebeim.client.bean.DataSource;
import cn.nawang.ebeim.client.bean.TaskStatusBean;
import cn.nawang.ebeim.client.bean.UploadProcessBarBean;
import cn.nawang.ebeim.client.bean.UserBehaviorsLog;
import cn.nawang.ebeim.client.exception.ApiRequestException;
import cn.nawang.ebeim.client.util.ApiUtil;
import cn.nawang.ebeim.client.util.ApiVisitUtil;
import cn.nawang.ebeim.client.util.CommonMethodsUtils;
import cn.nawang.ebeim.client.util.Constants;
import cn.nawang.ebeim.client.util.DbUpDownloadUtil;
import cn.nawang.ebeim.client.util.DbUtil;
import cn.nawang.ebeim.client.util.DealUnfinishTask;
import cn.nawang.ebeim.client.util.FileUtil;
import cn.nawang.ebeim.client.util.RunningDsIds;
import cn.nawang.ebeim.client.util.RunningDsIds.CurrentExitsDsId;
import cn.nawang.ebeim.client.util.UploadProcessBarList;
import cn.nawang.ebeim.client.util.UserBehaviorsUploadUtils;

/**
 * @ClassName: TaskStatusThread
 * @Description: 任务完成状态线程
 * @author 张建峰
 * @date 2015年8月25日 下午2:09:40
 * @version v1.0
 */
public class TaskStatusThread implements Runnable {
  private static final Logger LOG = LoggerFactory.getLogger(TaskStatusThread.class);
  private int timer = 0;

  @Override
  public void run() {
    RunningDsIds.setCheckExitsDsId(new CurrentExitsDsId() {

      @Override
      public String findId(String id) {
        return findFinishId(id);
      }
    });

    while (true) {
      Set<String> removeSet = RunningDsIds.executeIterator();
      // timer++;
      //
      // if (timer >= 3) {
      RunningDsIds.remove(removeSet);
      // timer = 0;
      // }
      try {
        Thread.sleep(1000 * 10);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

  }


  private String findFinishId(String dsId) {

    int count = DbUtil.getTaskStatusFileUnfinishedCount(DbUtil.TASK_TYPE_FILE, dsId);
    LOG.info("TaskStatusThread..........dsId:" + dsId);
    LOG.info("TaskStatusThread..........getTaskStatusFileUnfinishedCount:" + count);
    /** 表示该数据源下所有文件都已上传成功 */
    if (count == 0) {
      
      long spaceUsage = DbUtil.getTaskStatusFileFinishedFileSizeSum(DbUtil.TASK_TYPE_FILE, dsId);

      DataSource datasource = ApiUtil.getDataSource(dsId);

      if (datasource == null) {
        Log.info("获取服务端数据源状态失败" + dsId);
        return null;
      }

      if (datasource.getStatus() == Constants.DS_RUN_STATUS_RUNNING) {
        long newSpaceUsage = 0;
        if (datasource.getSpaceUsage() == null) {
          newSpaceUsage = spaceUsage;
        } else {
          newSpaceUsage = datasource.getSpaceUsage() + spaceUsage;
        }
        DataSource newDs = new DataSource();
        newDs.setId(datasource.getId());
        newDs.setSpaceUsage(newSpaceUsage);
        // 数据源置位成未执行状态
        newDs.setStatus(Constants.DS_RUN_STATUS_SUCCESS);
        String result = ApiVisitUtil.updataDatasource(newDs);
        if (!"success".equals(result)) {
          Log.info("更改服务端数据源状态失败" + dsId);
          return null;
        }
      }

      DbUtil.deleteTaskStatusFile(dsId);


      List<String> removeProcessList = new ArrayList<String>();
      for (String key : UploadProcessBarList.total.keySet()) {
        UploadProcessBarBean bean =
            DbUpDownloadUtil.getUploadProcessBar(key, DbUpDownloadUtil.PROCESS_BAR_STATUS_RUNNING);
        if (bean != null) {
          if (bean.getCount() >= bean.getTotal()
              || (bean.getOkSum() + bean.getErrorSum()) >= bean.getFileSum()) {
            DbUpDownloadUtil.updateUploadProcessBarStatus(bean.getDsId(),
                DbUpDownloadUtil.PROCESS_BAR_STATUS_SUCCESS);
            LOG.info(".......bean.getCount() >= bean.getTotal().......");
            removeProcessList.add(key);
          }
        }
      }
      for (int i = 0; i < removeProcessList.size(); i++) {
        String key = removeProcessList.get(i);
        UploadProcessBarList.total.remove(key);
      }

      // 日志处理
      CommonMethodsUtils.backupLogProcess(datasource.getId(),
          datasource.getCurrentVersion().getMajorVersion(),
          datasource.getCurrentVersion().getMinorVersion(), Constants.BACKUPLOG_STATUS_SUCCESS,
          spaceUsage, "备份成功!");
      
      ClientConfiguration.isRunningList.remove(dsId);

      FileUtil.deleteDir(
          new File(FileUtil.getDataSourcePath(dsId) + File.separator + FileUtil.PATH_UPLOAD));
      UserBehaviorsUploadUtils.uploadAllFile(dsId, UserBehaviorsLog.ACTION_UPLOAD);
      return dsId;
    } else {
      List<TaskStatusBean> breakPointBeans = DbUtil.getTaskStatusBreakPoint(dsId);
      for (TaskStatusBean taskStatusBean : breakPointBeans) {
        taskStatusBean.setTryCount(1);
        try {
          if (taskStatusBean.getType() == DbUtil.TASK_TYPE_FILE) {
            DbUtil.updateTaskStatusFile(taskStatusBean.getDsId(), taskStatusBean.getSignature(),
            DbUtil.TASK_STATUS_RUNNING);
          } else if (taskStatusBean.getType() == DbUtil.TASK_TYPE_VERSION) {
            DbUtil.updateTaskStatusVersion(taskStatusBean.getDsId(),
                taskStatusBean.getVersion().getMajorVersion(),
                taskStatusBean.getVersion().getMinorVersion(), DbUtil.TASK_STATUS_RUNNING);
          }
          BreakPointQueue.enqueue(taskStatusBean);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }

      return null;
    }
  }

}
